<template>
  <a-modal
    :title="title"
    :width="1200"
    :visible="visible"
    @cancel="handleCancel"
    :footer="null">
    
    <a-spin :spinning="confirmLoading">
      <!-- 采购单基本信息 -->
      <a-card :bordered="false" title="采购单基本信息" style="margin-bottom: 16px">
        <a-descriptions bordered :column="3" size="small">
          <a-descriptions-item label="采购单号">{{ purchaseOrder.purchaseNo }}</a-descriptions-item>
          <a-descriptions-item label="预计到货日期">{{ purchaseOrder.expectedArrivalDate }}</a-descriptions-item>
          <a-descriptions-item label="总金额">¥{{ purchaseOrder.totalAmount ? parseFloat(purchaseOrder.totalAmount).toFixed(2) : '0.00' }}</a-descriptions-item>
          <a-descriptions-item label="状态">
            <a-tag :color="getStatusColor(purchaseOrder.status)">
              <j-dict-tag v-if="purchaseOrder.status" :value="purchaseOrder.status || ''" dictCode="purchase_order_status"/>
              <span v-else>-</span>
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="退换货状态">
            <a-tag :color="getReturnExchangeStatusColor(purchaseOrder.returnExchangeStatus)">
              <j-dict-tag v-if="purchaseOrder.returnExchangeStatus != null" :value="purchaseOrder.returnExchangeStatus || ''" dictCode="return_exchange_status"/>
              <span v-else>-</span>
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="是否自动生成">
            <a-tag :color="purchaseOrder.isAutoGenerated ? 'blue' : 'green'">
              {{ purchaseOrder.isAutoGenerated ? '自动生成' : '手动创建' }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="创建人">{{ purchaseOrder.createBy }}</a-descriptions-item>
          <a-descriptions-item label="创建时间">{{ purchaseOrder.createTime }}</a-descriptions-item>
          <a-descriptions-item label="审核人">{{ purchaseOrder.approveBy || '-' }}</a-descriptions-item>
          <a-descriptions-item label="审核时间">{{ purchaseOrder.approveTime || '-' }}</a-descriptions-item>
          <a-descriptions-item label="备注" :span="3">{{ purchaseOrder.remark || '-' }}</a-descriptions-item>
        </a-descriptions>
      </a-card>
      
      <!-- 采购单明细 -->
      <a-card :bordered="false" title="采购单明细">
        <a-table
          ref="table"
          size="middle"
          bordered
          rowKey="id"
          :columns="columns"
          :dataSource="detailList"
          :pagination="false"
          :scroll="{ x: 1500 }">
          
          <!-- 物料图片列 -->
          <template slot="materialImageSlot" slot-scope="text">
            <div v-if="text" class="material-thumbnail-container">
              <a-carousel dots-position="bottom" arrows autoplay>
                <div v-for="(img, index) in getImagesArray(text)" :key="index" class="material-image-item">
                  <img
                    :src="getImageUrl(img)"
                    class="material-thumbnail"
                    alt="物料图片"
                    @click="handlePreviewImage(img)"
                    @error="handleImageError"
                  />
                </div>
              </a-carousel>
            </div>
            <span v-else>-</span>
          </template>
          
          <!-- 金额列 -->
          <template slot="amountSlot" slot-scope="text">
            {{ text ? '¥' + parseFloat(text).toFixed(2) : '¥0.00' }}
          </template>
          
          <!-- 单价列 -->
          <template slot="unitPriceSlot" slot-scope="text">
            {{ text ? '¥' + parseFloat(text).toFixed(2) : '¥0.00' }}
          </template>
          
          <!-- 物料类型列 -->
          <template slot="materialTypeSlot" slot-scope="text">
            <a-tag v-if="text" :color="
              text == '1' ? 'blue' : 
              text == '2' ? 'green' : 
              text == '3' ? 'orange' : 
              text == '4' ? 'purple' : 
              text == '5' ? 'red' : 
              text == '6' ? 'yellow' : ''"
            >
              {{ 
                text == '1' ? '型材' : 
                text == '2' ? '配件' : 
                text == '3' ? '辅件' : 
                text == '4' ? '其他' : 
                text == '5' ? '余料' : 
                text == '6' ? '半料' : '-'
              }}
            </a-tag>
            <span v-else>-</span>
          </template>
          
          <!-- 交货周期列 -->
          <template slot="leadTimeSlot" slot-scope="text">
            {{ text ? text + '天' : '-' }}
          </template>
        </a-table>
        
        <div style="text-align: right; margin-top: 12px;">
          <span style="margin-right: 12px;">总金额: <b style="color: #f5222d; font-size: 16px;">
            ¥{{ purchaseOrder.totalAmount ? parseFloat(purchaseOrder.totalAmount).toFixed(2) : '0.00' }}
          </b></span>
        </div>
      </a-card>
      
      <!-- 质检明细 - 仅在采购单状态为已到货或部分到货时显示 -->
      <template v-if="purchaseOrder.status == '7' || purchaseOrder.status == '8'">
        <!-- 质检合格明细 -->
        <a-card :bordered="false" title="质检合格明细" style="margin-top: 16px;">
          <a-table
            ref="qualifiedTable"
            size="middle"
            bordered
            rowKey="id"
            :columns="inspectionColumns"
            :dataSource="qualifiedList"
            :pagination="false"
            :scroll="{ x: 1300 }">
            
            <!-- 物料类型列 -->
            <template slot="materialTypeSlot" slot-scope="text">
              <a-tag v-if="text" :color="
                text == '1' ? 'blue' : 
                text == '2' ? 'green' : 
                text == '3' ? 'orange' : 
                text == '4' ? 'purple' : 
                text == '5' ? 'red' : 
                text == '6' ? 'yellow' : ''"
              >
                {{ 
                  text == '1' ? '型材' : 
                  text == '2' ? '配件' : 
                  text == '3' ? '辅件' : 
                  text == '4' ? '其他' : 
                  text == '5' ? '余料' : 
                  text == '6' ? '半料' : '-'
                }}
              </a-tag>
              <span v-else>-</span>
            </template>
            
            <!-- 凭证列 -->
            <template slot="evidenceSlot" slot-scope="text">
              <div v-if="text" class="material-thumbnail-container">
                <img
                  :src="getImageUrl(text)"
                  class="material-thumbnail"
                  alt="凭证"
                  @click="handlePreviewImage(text)"
                  @error="handleImageError"
                />
              </div>
              <span v-else>-</span>
            </template>
          </a-table>
        </a-card>
        
        <!-- 质检不合格明细 -->
        <a-card v-if="unqualifiedList.length > 0" :bordered="false" title="质检不合格明细" style="margin-top: 16px;">
          <div class="table-operator" style="margin-bottom: 16px;">
            <a-button type="primary" icon="rollback" :disabled="selectedUnqualifiedRows.length === 0 || hasProcessedRecords" @click="handleBatchReturn">批量退货</a-button>
            <a-button style="margin-left: 8px" icon="sync" :disabled="selectedUnqualifiedRows.length === 0 || hasProcessedRecords" @click="handleBatchExchange">批量换货</a-button>
            <span v-if="hasProcessedRecords" style="color: #ff4d4f; margin-left: 8px;">
              <a-icon type="warning" /> 已处理的记录不能进行退换货操作
            </span>
          </div>
          
          <a-table
            ref="unqualifiedTable"
            size="middle"
            bordered
            rowKey="id"
            :columns="unqualifiedColumns"
            :dataSource="unqualifiedList"
            :pagination="false"
            :rowSelection="{
              selectedRowKeys: selectedUnqualifiedRowKeys,
              onChange: onUnqualifiedSelectChange,
              getCheckboxProps: record => ({
                disabled: record.status === 1 // 已处理的记录禁用选择
              })
            }"
            :scroll="{ x: 1300 }">
            
            <!-- 物料类型列 -->
            <template slot="materialTypeSlot" slot-scope="text">
              <a-tag v-if="text" :color="
                text == '1' ? 'blue' : 
                text == '2' ? 'green' : 
                text == '3' ? 'orange' : 
                text == '4' ? 'purple' : 
                text == '5' ? 'red' : 
                text == '6' ? 'yellow' : ''"
              >
                {{ 
                  text == '1' ? '型材' : 
                  text == '2' ? '配件' : 
                  text == '3' ? '辅件' : 
                  text == '4' ? '其他' : 
                  text == '5' ? '余料' : 
                  text == '6' ? '半料' : '-'
                }}
              </a-tag>
            </template>
            
            <!-- 凭证列 -->
            <template slot="evidenceSlot" slot-scope="text">
              <div v-if="text" class="material-thumbnail-container">
                <img
                  :src="getImageUrl(text)"
                  class="material-thumbnail"
                  alt="凭证"
                  @click="handlePreviewImage(text)"
                  @error="handleImageError"
                />
              </div>
              <span v-else>-</span>
            </template>

            <!-- 处理状态列 -->
            <template slot="statusSlot" slot-scope="text">
              <a-tag :color="text == 1 ? 'green' : 'red'">
                {{ text == 1 ? '已处理' : '未处理' }}
              </a-tag>
            </template>
          </a-table>
        </a-card>
      </template>
      
      <div style="text-align: center; margin-top: 16px;">
        <a-button @click="handleCancel">关闭</a-button>
      </div>
    </a-spin>
    
    <!-- 图片预览模态框 -->
    <a-modal :visible="previewVisible" :footer="null" @cancel="previewVisible = false">
      <img alt="物料图片" style="width: 100%" :src="previewImage" />
    </a-modal>

    <!-- 退货/换货模态框 -->
    <purchase-return-exchange-modal ref="returnExchangeModal" @ok="loadInspectionList(purchaseOrder.id)"></purchase-return-exchange-modal>
  </a-modal>
</template>

<script>
import { getAction } from '@/api/manage'
import JDictTag from '@/components/dict/JDictTag'
import { getFileAccessHttpUrl } from '@/api/manage'
import PurchaseReturnExchangeModal from './PurchaseReturnExchangeModal'

export default {
  name: 'PurchaseOrderDetail',
  components: {
    JDictTag,
    PurchaseReturnExchangeModal
  },
  data() {
    return {
      title: '采购单详情',
      visible: false,
      confirmLoading: false,
      purchaseOrder: {
        status: '', // 初始化状态字段为空字符串，避免undefined
        purchaseNo: '',
        expectedArrivalDate: '',
        totalAmount: 0,
        remark: '',
        createBy: '',
        createTime: '',
        approveBy: '',
        approveTime: '',
        isAutoGenerated: 0,
        returnExchangeStatus: null // 初始化退换货状态字段
      },
      detailList: [],
      // 图片预览相关
      previewVisible: false,
      previewImage: '',
      // 不合格明细选择相关
      selectedUnqualifiedRowKeys: [],
      selectedUnqualifiedRows: [],
      hasProcessedRecords: false, // 是否有已处理的记录
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: "center",
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          }
        },
        {
          title: '物料编码',
          align: "center",
          dataIndex: 'materialCode',
          width: 120
        },
        {
          title: '物料名称',
          align: "center",
          dataIndex: 'materialName',
          width: 150
        },
        {
          title: '物料图片',
          align: "center",
          dataIndex: 'materialImage',
          width: 100,
          scopedSlots: { customRender: 'materialImageSlot' }
        },
        {
          title: '物料类型',
          align: "center",
          dataIndex: 'materialType',
          width: 100,
          scopedSlots: { customRender: 'materialTypeSlot' }
        },
        {
          title: '规格型号',
          align: "center",
          dataIndex: 'specification',
          width: 120
        },
        {
          title: '供应商',
          align: "center",
          dataIndex: 'supplierName',
          width: 150
        },
        {
          title: '单位',
          align: "center",
          dataIndex: 'unit',
          width: 80
        },
        {
          title: '数量',
          align: "center",
          dataIndex: 'quantity',
          width: 100
        },
        {
          title: '单价',
          align: "center",
          dataIndex: 'unitPrice',
          width: 100,
          scopedSlots: { customRender: 'unitPriceSlot' }
        },
        {
          title: '交货周期',
          align: "center",
          dataIndex: 'leadTime',
          width: 100,
          scopedSlots: { customRender: 'leadTimeSlot' }
        },
        {
          title: '金额',
          align: "center",
          dataIndex: 'amount',
          width: 100,
          scopedSlots: { customRender: 'amountSlot' }
        },
        {
          title: '已入库数量',
          align: "center",
          dataIndex: 'receivedQuantity',
          width: 100
        },
        {
          title: '备注',
          align: "center",
          dataIndex: 'remark',
          width: 150
        }
      ],
      url: {
        detail: '/wms/purchase/queryById',
        detailList: '/wms/purchase/detail/list',
        inspectionList: '/wms/purchase/getInspectionList'
      },
      // 质检明细相关
      qualifiedList: [],
      unqualifiedList: [],
      inspectionColumns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: "center",
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          }
        },
        {
          title: '物料编码',
          align: "center",
          dataIndex: 'materialCode',
          width: 120
        },
        {
          title: '物料名称',
          align: "center",
          dataIndex: 'materialName',
          width: 150
        },
        {
          title: '物料类型',
          align: "center",
          dataIndex: 'materialType',
          width: 100,
          scopedSlots: { customRender: 'materialTypeSlot' }
        },
        {
          title: '规格型号',
          align: "center",
          dataIndex: 'specification',
          width: 120
        },
        {
          title: '供应商',
          align: "center",
          dataIndex: 'supplierName',
          width: 150
        },
        {
          title: '单位',
          align: "center",
          dataIndex: 'unit',
          width: 80
        },
        {
          title: '到货数量',
          align: "center",
          dataIndex: 'arrivalQuantity',
          width: 100
        },
        {
          title: '合格数量',
          align: "center",
          dataIndex: 'qualifiedQuantity',
          width: 100
        },
        {
          title: '到货日期',
          align: "center",
          dataIndex: 'arrivalDate',
          width: 120
        },
        {
          title: '凭证',
          align: "center",
          dataIndex: 'evidence',
          width: 100,
          scopedSlots: { customRender: 'evidenceSlot' }
        },
        {
          title: '备注',
          align: "center",
          dataIndex: 'remark',
          width: 150
        }
      ],
      unqualifiedColumns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: "center",
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          }
        },
        {
          title: '物料编码',
          align: "center",
          dataIndex: 'materialCode',
          width: 120
        },
        {
          title: '物料名称',
          align: "center",
          dataIndex: 'materialName',
          width: 150
        },
        {
          title: '物料类型',
          align: "center",
          dataIndex: 'materialType',
          width: 100,
          scopedSlots: { customRender: 'materialTypeSlot' }
        },
        {
          title: '规格型号',
          align: "center",
          dataIndex: 'specification',
          width: 120
        },
        {
          title: '供应商',
          align: "center",
          dataIndex: 'supplierName',
          width: 150
        },
        {
          title: '单位',
          align: "center",
          dataIndex: 'unit',
          width: 80
        },
        {
          title: '不合格数量',
          align: "center",
          dataIndex: 'unqualifiedQuantity',
          width: 100
        },
        {
          title: '不合格原因',
          align: "center",
          dataIndex: 'unqualifiedReason',
          width: 150
        },
        {
          title: '到货日期',
          align: "center",
          dataIndex: 'arrivalDate',
          width: 120
        },
        {
          title: '凭证',
          align: "center",
          dataIndex: 'evidence',
          width: 100,
          scopedSlots: { customRender: 'evidenceSlot' }
        },
        {
          title: '处理状态',
          align: "center",
          dataIndex: 'status',
          width: 100,
          scopedSlots: { customRender: 'statusSlot' }
        },
        {
          title: '备注',
          align: "center",
          dataIndex: 'remark',
          width: 150
        }
      ]
    }
  },
  methods: {
    show(id) {
      this.visible = true;
      this.loadData(id);
    },
    loadData(id) {
      this.confirmLoading = true;
      
      // 加载采购单基本信息
      getAction(this.url.detail, { id }).then(res => {
        if (res.success && res.result) {
          // 使用Object.assign合并对象，确保所有属性都存在
          this.purchaseOrder = Object.assign({
            status: '',
            purchaseNo: '',
            expectedArrivalDate: '',
            totalAmount: 0,
            remark: '',
            createBy: '',
            createTime: '',
            approveBy: '',
            approveTime: '',
            isAutoGenerated: 0,
            returnExchangeStatus: null // 重置退换货状态
          }, res.result);
          
          // 加载采购单明细
          this.loadDetailList(id);
          
          // 如果是已到货或部分到货状态，加载质检明细
          if (this.purchaseOrder.status == '7' || this.purchaseOrder.status == '8') {
            this.loadInspectionList(id);
          }
        } else {
          this.$message.error(res.message || '加载采购单详情失败');
          this.confirmLoading = false;
        }
      }).catch(() => {
        this.confirmLoading = false;
      });
    },
    loadDetailList(purchaseOrderId) {
      getAction(this.url.detailList, { purchaseOrderId }).then(res => {
        if (res.success) {
          this.detailList = res.result || [];
        } else {
          this.$message.error(res.message || '加载采购单明细失败');
        }
        
        // 如果没有其他请求，则取消加载状态
        if (!(this.purchaseOrder.status == '7' || this.purchaseOrder.status == '8')) {
          this.confirmLoading = false;
        }
      }).catch(() => {
        this.confirmLoading = false;
      });
    },
    loadInspectionList(purchaseOrderId) {
      getAction(this.url.inspectionList, { purchaseOrderId }).then(res => {
        if (res.success && res.result) {
          // 分离合格和不合格的质检记录
          this.qualifiedList = res.result.filter(item => item.inspectionResult == 1);
          this.unqualifiedList = res.result.filter(item => item.inspectionResult == 0);
        } else {
          this.$message.error(res.message || '加载质检明细失败');
        }
        this.confirmLoading = false;
      }).catch(() => {
        this.confirmLoading = false;
      });
    },
    getStatusColor(status) {
      // 如果状态为空，返回默认颜色
      if (!status) {
        return 'default';
      }
      
      // 状态颜色映射
      const statusColorMap = {
        '1': 'blue',    // 草稿
        '2': 'orange',  // 待审批
        '3': 'green',   // 已审批
        '4': 'cyan',    // 部分入库
        '5': 'purple',  // 已完成
        '6': 'red',      // 已取消
        '7': 'blue',      // 已到货
        '8': 'yellow'      // 部分到货
      }
      return statusColorMap[status] || 'default';
    },
    getReturnExchangeStatusColor(status) {
      // 退换货状态颜色映射
      const statusColorMap = {
        0: 'green', // 无需退换货
        1: 'orange', // 等待处理
        2: 'red', // 退货
        3: 'blue', // 换货
      }
      return statusColorMap[status] || 'default';
    },
    handleCancel() {
      this.visible = false;
      // 重置为初始状态而不是空对象
      this.purchaseOrder = {
        status: '',
        purchaseNo: '',
        expectedArrivalDate: '',
        totalAmount: 0,
        remark: '',
        createBy: '',
        createTime: '',
        approveBy: '',
        approveTime: '',
        isAutoGenerated: 0,
        returnExchangeStatus: null // 重置退换货状态
      };
      this.detailList = [];
      this.qualifiedList = [];
      this.unqualifiedList = [];
      this.selectedUnqualifiedRowKeys = [];
      this.selectedUnqualifiedRows = [];
      this.hasProcessedRecords = false; // 重置已处理记录状态
      
      // 通知父组件刷新数据
      this.$emit('refresh');
    },
    handlePrint() {
      this.$message.info('打印功能开发中');
      // 实际项目中可以调用打印API或使用打印插件
    },
    // 图片相关方法
    getImageUrl(text) {
      if (!text) return '';
      try {
        return getFileAccessHttpUrl(text);
      } catch (error) {
        console.error('获取文件URL失败:', error);
        return '';
      }
    },
    handlePreviewImage(text) {
      this.previewImage = this.getImageUrl(text);
      this.previewVisible = true;
    },
    handleImageError(e) {
      e.target.src = '';
      e.target.alt = '图片加载失败';
    },
    // 将图片字符串转换为数组
    getImagesArray(text) {
      if (!text) return [];
      return text.split(',').filter(Boolean);
    },
    // 行选择变化
    onUnqualifiedSelectChange(selectedRowKeys, selectedRows) {
      this.selectedUnqualifiedRowKeys = selectedRowKeys;
      this.selectedUnqualifiedRows = selectedRows;
      
      // 检查是否有已处理的记录被选中
      this.hasProcessedRecords = selectedRows.some(row => row.status === 1);
    },
    
    // 批量退货
    handleBatchReturn() {
      if (this.selectedUnqualifiedRows.length == 0) {
        this.$message.warning('请至少选择一条不合格记录');
        return;
      }
      
      // 如果只选择了一条记录，直接调用单个退货方法
      if (this.selectedUnqualifiedRows.length == 1) {
        this.handleReturn(this.selectedUnqualifiedRows[0]);
        return;
      }
      
      // 批量退货处理
      this.$confirm({
        title: '批量退货',
        content: `确定要对选中的 ${this.selectedUnqualifiedRows.length} 条不合格记录进行退货操作吗？`,
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          // 找出对应的采购单明细以获取单价信息
          const detailMap = {};
          this.detailList.forEach(detail => {
            detailMap[detail.materialId] = detail;
          });

          // 创建批量退货单
          const batchReturnData = {
            purchaseOrderId: this.purchaseOrder.id,
            purchaseOrderNo: this.purchaseOrder.purchaseNo,
            type: 1, // 1-退货
            items: this.selectedUnqualifiedRows.map(row => {
              const detail = detailMap[row.materialId] || {};
              return {
                inspectionId: row.id,
                materialId: row.materialId,
                materialCode: row.materialCode,
                materialName: row.materialName,
                materialType: row.materialType,
                specification: row.specification,
                unit: row.unit,
                unqualifiedQuantity: row.unqualifiedQuantity,
                supplierId: row.supplierId,
                supplierName: row.supplierName,
                unitPrice: detail.unitPrice || 0 // 添加单价信息
              };
            })
          };
          
          this.$refs.returnExchangeModal.showBatch(batchReturnData);
        }
      });
    },
    
    // 批量换货
    handleBatchExchange() {
      if (this.selectedUnqualifiedRows.length == 0) {
        this.$message.warning('请至少选择一条不合格记录');
        return;
      }
      
      // 如果只选择了一条记录，直接调用单个换货方法
      if (this.selectedUnqualifiedRows.length == 1) {
        this.handleExchange(this.selectedUnqualifiedRows[0]);
        return;
      }
      
      // 批量换货处理
      this.$confirm({
        title: '批量换货',
        content: `确定要对选中的 ${this.selectedUnqualifiedRows.length} 条不合格记录进行换货操作吗？`,
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          // 找出对应的采购单明细以获取单价信息
          const detailMap = {};
          this.detailList.forEach(detail => {
            detailMap[detail.materialId] = detail;
          });

          // 创建批量换货单
          const batchExchangeData = {
            purchaseOrderId: this.purchaseOrder.id,
            purchaseOrderNo: this.purchaseOrder.purchaseNo,
            type: 2, // 2-换货
            items: this.selectedUnqualifiedRows.map(row => {
              const detail = detailMap[row.materialId] || {};
              return {
                inspectionId: row.id,
                materialId: row.materialId,
                materialCode: row.materialCode,
                materialName: row.materialName,
                materialType: row.materialType,
                specification: row.specification,
                unit: row.unit,
                unqualifiedQuantity: row.unqualifiedQuantity,
                supplierId: row.supplierId,
                supplierName: row.supplierName,
                unitPrice: detail.unitPrice || 0 // 添加单价信息
              };
            })
          };
          
          this.$refs.returnExchangeModal.showBatch(batchExchangeData);
        }
      });
    },
    
    // 单个退货处理
    handleReturn(record) {
      // 找出对应的采购单明细以获取单价信息
      const detail = this.detailList.find(item => item.materialId === record.materialId) || {};
      
      this.$refs.returnExchangeModal.show({
        purchaseOrderId: this.purchaseOrder.id,
        purchaseOrderNo: this.purchaseOrder.purchaseNo,
        inspectionId: record.id,
        materialId: record.materialId,
        materialCode: record.materialCode,
        materialName: record.materialName,
        materialType: record.materialType,
        specification: record.specification,
        unit: record.unit,
        unqualifiedQuantity: record.unqualifiedQuantity,
        supplierId: record.supplierId,
        supplierName: record.supplierName,
        unitPrice: detail.unitPrice || 0, // 添加单价信息
        type: 1 // 1-退货
      });
    },

    // 单个换货处理
    handleExchange(record) {
      // 找出对应的采购单明细以获取单价信息
      const detail = this.detailList.find(item => item.materialId === record.materialId) || {};
      
      this.$refs.returnExchangeModal.show({
        purchaseOrderId: this.purchaseOrder.id,
        purchaseOrderNo: this.purchaseOrder.purchaseNo,
        inspectionId: record.id,
        materialId: record.materialId,
        materialCode: record.materialCode,
        materialName: record.materialName,
        materialType: record.materialType,
        specification: record.specification,
        unit: record.unit,
        unqualifiedQuantity: record.unqualifiedQuantity,
        supplierId: record.supplierId,
        supplierName: record.supplierName,
        unitPrice: detail.unitPrice || 0, // 添加单价信息
        type: 2 // 2-换货
      });
    }
  }
}
</script>

<style scoped>
.material-thumbnail-container {
  width: 80px;
  height: 60px;
  margin: 0 auto;
  overflow: hidden;
}

.material-thumbnail {
  max-width: 80px;
  max-height: 60px;
  cursor: pointer;
  object-fit: contain;
}

/* 自定义轮播图样式 */
.material-thumbnail-container .ant-carousel {
  height: 100%;
}

.material-thumbnail-container .ant-carousel .slick-slide {
  height: 60px;
  line-height: 60px;
  text-align: center;
}

.material-thumbnail-container .ant-carousel .slick-dots {
  margin: 0;
  padding: 0;
  height: 12px;
  bottom: 0;
}

.material-thumbnail-container .ant-carousel .slick-dots li button {
  width: 6px;
  height: 6px;
}
</style> 